package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //2.1 设置布尔查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字的分词之后查询
        boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));
        //查询小于mindate的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));
        searchRequest.source().query(boolQueryBuilder);

        //2.2 设置分页查询
        searchRequest.source().from(0);
        searchRequest.source().size(dto.getPageSize());

        //2.3 按照发布时间倒序查询
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        //2.4 设置高亮  title
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchRequest.source().highlighter(highlightBuilder);
        //2.5 发送请求，查询ES
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //3.结果封装返回
        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0) {
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title", title);
            } else {
                //原始标题
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }

        //异步调用保存搜索历史记录的功能
        //只有当前登录用户不为空并且用户在首页搜索，才进行历史记录的保存
        if (AppThreadLocalUtils.getUser() != null && dto.getFromIndex() == 0) {
            apUserSearchService.insert(dto.getSearchWords(), AppThreadLocalUtils.getUser().getId());
        }
        return ResponseResult.okResult(list);
    }
//        //数据校验
//        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
//        //查询条件分装
//        SearchRequest searchRequest = new SearchRequest();
//        //布尔查询
//        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
//        //分词过后查询
//        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content");
//        boolQueryBuilder.must(multiMatchQueryBuilder);
//
//        //查询小于mindata的数据
//        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
//        searchRequest.source().query(boolQueryBuilder)
//        //设置分页 设置 页数
//        searchRequest.source().size(dto.getPageSize());
//        searchRequest.source().from(0);
//        //时间倒叙查询
//        searchRequest.source().sort("publishTime",SortOrder.DESC);
//        //高亮显示
//        HighlightBuilder highlightBuilder=new HighlightBuilder();
//        highlightBuilder.field("title");
//        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
//        highlightBuilder.postTags("</font>");
//        searchRequest.source().highlighter(highlightBuilder);
//        //获得结果集
//        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        //获取高亮结果 返回给前端
//
//
//        SearchHit[] hits = searchResponse.getHits().getHits();
//        for (SearchHit hit : hits) {
//            String json = hit.getSourceAsString();
//            Map map = JSON.parseObject(json, Map.class);
//            if (hit.getHighlightFields().size() > 0||hit.getHighlightFields()!=null) {
//                Text[] titles = hit.getHighlightFields().get("title").getFragments();
//                String title = JSON.toJSONString(titles);
//                map.put("h_title", title);
//            }else {
//                map.put("h_title",map.get("title"))
//            }
//        }
//
//    }
}